
from alipay import AliPay
from config import BASE as BasePath
from config import DEBUG,ALIPAY_APPID,ALIPAY_NOTIFY_URL,ALIPAY_REDICT,DOMAIN
import os,requests

class AliPayComponent:

    def __init__(self):

        private,public = self.__load_key()

        self.private = private
        self.public = public

        self.app = alipay = AliPay(
            appid=ALIPAY_APPID,
            app_notify_url=ALIPAY_NOTIFY_URL,  # 默认回调url
            app_private_key_string=private,
            # 支付宝的公钥，验证支付宝回传消息使用
            alipay_public_key_string=public,
            sign_type="RSA2",
            debug=True  # 默认False
        )



    def __load_key(self):
        private = open(os.path.join(BasePath,'rsa/app_private_key.pem'))
        public = open(os.path.join(BasePath,'rsa/alipay_public_key.pem'))
        app_private_key_string = private.read()
        alipay_public_key_string = public.read()
        private.close()
        public.close()
        return app_private_key_string,alipay_public_key_string



    def make_trade_for_phone(self,subject,price,order_number,return_url=None):

        order_string = self.app.api_alipay_trade_wap_pay(
            out_trade_no=order_number,
            total_amount=price,
            subject=subject,
            return_url=return_url if return_url else '%s/api/alipay/callback/'%(DOMAIN)
        )

        return '%s?%s'%(ALIPAY_REDICT,order_string)


    def make_trade_for_pc(self,subject,price,order_number,return_url=None):
        order_string = self.app.api_alipay_trade_page_pay(
            out_trade_no=order_number,
            total_amount=price,
            subject=subject,
            return_url=return_url if return_url else '%s/api/alipay/callback/'%(DOMAIN)
        )

        return '%s?%s'%(ALIPAY_REDICT,order_string)
        
    def verify(self,data,signature):
        return self.app.verify(data,signature)

    def transfer(self,payee_account,amount,payee_real_name,out_biz_no):

        response = self.app.api_alipay_fund_trans_toaccount_transfer(
            out_biz_no=out_biz_no,
            payee_type = 'ALIPAY_LOGONID',
            payee_account = payee_account,
            amount=amount,
            payee_real_name=payee_real_name,
            remark='佣金提现'
        )

        return response